package com.seele.tigerwallet.ui.activtiy;

import android.Manifest;
import android.content.Intent;
import android.os.Handler;
import android.os.Vibrator;
import android.support.annotation.NonNull;
import android.support.v4.hardware.fingerprint.FingerprintManagerCompat;
import android.support.v7.widget.RecyclerView;
import android.view.Gravity;
import android.view.View;
import android.view.WindowManager;
import android.view.animation.Animation;
import android.view.animation.AnimationUtils;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.seele.tigerwallet.R;
import com.seele.tigerwallet.async.Log;
import com.seele.tigerwallet.ui.base.TitleBaseActivity;
import com.seele.tigerwallet.ui.base.ToolbarBaseActivity;
import com.seele.tigerwallet.ui.utils.BaseDialog;
import com.seele.tigerwallet.ui.utils.DataUtils;
import com.seele.tigerwallet.ui.utils.FingerprintUtils;
import com.seele.tigerwallet.ui.utils.PermissionFail;
import com.seele.tigerwallet.ui.utils.PermissionSuccess;
import com.seele.tigerwallet.ui.utils.PermissionUtil;
import com.seele.tigerwallet.ui.utils.SPUtils;
import com.seele.tigerwallet.ui.views.LinearRelativeLayout;
import com.seele.tigerwallet.ui.views.SwipeItemLayout;
import com.seele.tigerwallet.ui.views.SwitchView;

/**
 * Description:系统设置界面
 * Data: 2018/6/11 17:36
 * author:  郑波
 */
public class SystemSetActivtiy extends ToolbarBaseActivity implements View.OnClickListener {

    private RelativeLayout mLanguageSelectRv;
    private RelativeLayout mTokenCompanyRv;
    private RelativeLayout mFingerprintRv;
    private FingerprintUtils mFingerprintUtils;


    public static final String SYSTEMSETACTIVTIY = "SystemSetActivtiy";
    private TextView mTokenCompanyTv;
    private final int PER_CAMERA = 24;
    private BaseDialog mBaseDialog;
    private SwitchView mSwitchView;
    private boolean isOpen;

    private TextView mTextView;

    private int count;
    private TextView mTitleTv;
    private TextView mContentTv;
    private TextView mPWTv;
    private LinearLayout mFingerprintLl;
    private int mFailedTimes;
    private Vibrator mVibrator;

    @Override
    public int getContainerViewId() {
        return R.layout.activity_system_set_activtiy;
    }

    @Override
    protected void initView() {
        setTitle(R.string.system_setup);
        mVibrator = (Vibrator) this.getSystemService(this.VIBRATOR_SERVICE);
        shake = AnimationUtils.loadAnimation(this, R.anim.shake);
        mLanguageSelectRv = $f(R.id.language_select_rv);
        mTokenCompanyRv = $f(R.id.token_company_rv);
        mTokenCompanyTv = $f(R.id.token_company_tv);
        mFingerprintRv = $f(R.id.fingerprint_rv);
        mSwitchView = $f(R.id.switchView);
        mLanguageSelectRv.setOnClickListener(this);
        mTokenCompanyRv.setOnClickListener(this);
        mSwitchView.setOnClickListener(this);
        if (null == mFingerprintUtils) {
            mFingerprintUtils = new FingerprintUtils();
        }
        mFingerprintUtils.init(this);
        mFingerprintUtils.isHardwareDetected();
//        setFingerprint();
        boolean fingerprints = SPUtils.getBoolean(SPUtils.FINGERPRINTS, false);
        mSwitchView.setOpened(fingerprints);

    }




    @Override
    protected void onResume() {
        mTokenCompanyTv.setText(DataUtils.getSystemCompany());
        super.onResume();
    }

    @Override
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.language_select_rv://语言选择

                Toast.makeText(SystemSetActivtiy.this, "正在开发中", Toast.LENGTH_SHORT).show();

                break;
            case R.id.token_company_rv://货币单位
                startActivity(TokenCompanySelectActivity.class);
                break;

            case R.id.switchView://指纹安全
                isOpen = mSwitchView.isOpened();
                Log.e("switchView", "::" + mSwitchView.isOpened());
                if (isOpen) {
                    PermissionUtil.needPermission(this, PER_CAMERA, Manifest.permission.USE_FINGERPRINT);

                    //获取权限
                    Log.e("switchView", ":开启指纹:");
                } else {
                    Log.e("switchView", ":关闭指纹:");
                    SPUtils.putBoolean(SPUtils.FINGERPRINTS, false);
                }

                break;
        }

    }


    @PermissionSuccess(requestCode = PER_CAMERA)
    private void grantPermissionSuccess() {
        startFingerprint();

    }

    @PermissionFail(requestCode = PER_CAMERA)
    private void grantPersmissionFail() {
        Toast.makeText(this, getResources().getString(R.string.read_external_storage), Toast.LENGTH_SHORT).show();
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        PermissionUtil.onRequestPermissionsResult(this, requestCode, permissions, grantResults);
    }




    View.OnClickListener onClickListener = new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            switch (view.getId()) {
                case R.id.cancel:
                    mSwitchView.setOpened(false);
                    if (null != mBaseDialog && mBaseDialog.isShowing()) {
                        mBaseDialog.dismiss();
                        mBaseDialog = null;
                    }
                    break;
            }

        }
    };


    private void startFingerprint() {
        if (mFingerprintUtils.hasEnrolledFingerprints()) {//指纹库有指纹
            initDialog();
            mFingerprintUtils.handlerFingerprint();
        } else {
            initDialog();
            setFingerprintDialog();
        }
    }


    /**
     * 设置指纹库没有指纹的样式
     */
    private void setFingerprintDialog() {
        if (null != mBaseDialog) {
            mBaseDialog.show();
            mTitleTv.setText(getResources().getString(R.string.move_to_the_security_center));
            mContentTv.setVisibility(View.GONE);
        }
    }


    /**
     * 初始化Dialo
     */
    private void initDialog() {
        if (null == mBaseDialog) {
            mBaseDialog = new BaseDialog.Builder(this).view(R.layout.dialog_fingerprint)
                    .setDialogPosition(Gravity.CENTER) //设置dialog显示位置
                    .cancelTouchout(false)//点击dialog背景不能取消dialog，默认为true

                    .setWidthPX((int) getResources().getDimension(R.dimen.dp_270))
                    .setHeightPX(WindowManager.LayoutParams.WRAP_CONTENT)
                    .addViewOnclick(R.id.cancel, onClickListener)
                    .addViewOnclick(R.id.transaction_pwd, onClickListener)
                    .build();
            mBaseDialog.setCancelable(false);
        }
        mTitleTv = mBaseDialog.findView(R.id.title_tv);
        mContentTv = mBaseDialog.findView(R.id.content_tv);
        mPWTv = mBaseDialog.findView(R.id.transaction_pwd);
        mTitleTv.setText(getResources().getString(R.string.fingerprint_title));
        mFingerprintLl = mBaseDialog.findView(R.id.fingerprint_ll);
        mPWTv.setVisibility(View.GONE);
        mBaseDialog.show();
        mFingerprintUtils.setFingerprintListener(onFingerprintListener);

    }

    /**
     * 指纹时间回调
     */
    private void setFingerprint() {
        mFingerprintUtils.setFingerprintListener(onFingerprintListener);
    }

    FingerprintUtils.OnFingerprintListener onFingerprintListener = new FingerprintUtils.OnFingerprintListener() {
        @Override
        public void onHardwareDetected(boolean hardwareDetected) {


        }

        @Override
        public void onEnrolledFingerprints(boolean b) {
        }

        @Override
        public void onAuthenticationError(int errorCode, CharSequence errString) {
            Log.e("setFingerprint", ":::onAuthenticationError");
            isOpen = false;
            if (errorCode == 7) {
                setFailedTimes(errorCode);


            }
        }

        @Override
        public void onAuthenticationHelp(int helpCode, CharSequence helpString) {

            if (helpCode == 1001) {
                if (null != mBaseDialog) {
//                        mFingerprintUtils.cancel();
                    mBaseDialog.show();
                }
            }
        }

        @Override
        public void onAuthenticationSucceeded(FingerprintManagerCompat.AuthenticationResult result) {
            isOpen = true;
            SPUtils.putBoolean(SPUtils.FINGERPRINTS, true);
            new Handler().postDelayed(new Runnable() {
                @Override
                public void run() {
                    if (null != mBaseDialog) {

                        mSwitchView.post(new Runnable() {
                            @Override
                            public void run() {
                                mSwitchView.setOpened(isOpen);
                            }
                        });
                        mBaseDialog.dismiss();

                    }
                }
            }, 600);
        }

        @Override
        public void onAuthenticationFailed() {
            isOpen = false;
            mFailedTimes++;
            setFailedTimes(mFailedTimes);


        }
    };

    Animation shake;

    private void setFailedTimes(int mFailedTimes) {
        if (mFailedTimes <= 3) {
            mVibrator.vibrate(500);
            mFingerprintLl.startAnimation(shake);
            mTitleTv.setText(getResources().getText(R.string.do_it_again));
//            mPWTv.setVisibility(View.VISIBLE);
        } else {
            if (null != mBaseDialog) {
                mBaseDialog.show();
                Log.e("setFailedTimes", ":111111111111111:");

//                mSwitchView.post(new Runnable() {
//                    @Override
//                    public void run() {
//                        mSwitchView.setOpened(isOpen);
//                    }
//                });
//                mBaseDialog.dismiss();
            }
            mTitleTv.setText(getResources().getText(R.string.multiple_errors));
            mFingerprintUtils.clearFingerprintListener();
        }

    }


    @Override
    protected void onDestroy() {
        count = 0;
//        mFingerprintUtils.cancel();
        super.onDestroy();
    }
}
